// import React, {Component} from 'react'
import {HashRouter as Router, Switch, Route, Redirect } from 'react-router-dom'
import { useReducer } from 'react'
import PrivateRoute from './components/PrivateRoute/PrivateRoute'
import routers, { login} from './router/index'
import consumerContext from './context/consumerContext'

import './App.less';

function reducer (state, action) {
  switch(action.type) {
    case 'setToken': 
      sessionStorage.setItem('token', action.payload.token)
      return {...state, token: action.payload.token}
    default: 
      throw new Error();
  }
}

function init() {
  const token = sessionStorage.getItem('token') || ''
  return {
    token
  }
}

function App() {
  const [state, dispatch] = useReducer(reducer, {}, init)

  return (
    <consumerContext.Provider value={{state, dispatch}}>
      <Router>
        <Switch>
          <Route exact path={login.path} component={login.component} />
          { routers.map((item, index) => {
              return <PrivateRoute key={index} path={item.path} component={item.component} />
            })
          }
          <Redirect from="/" to="login" />
        </Switch>
      </Router>
    </consumerContext.Provider>
  );
}

export default App;
